<template>
  <div>
    <transition name="fade" mode="out-in">
      <div v-if="searchable && searchPlace === 'top'" class="search-con search-con-top">
        <Select v-model="searchKey" class="search-col">
          <Option v-for="item in columns"
          v-if="item.key !== 'handle'"
          :value="item.key"
          :key="`search-col-${item.key}`"
          @click.native="setSearchTitle(item.title)"
          >{{ item.title }}</Option>
        </Select>
        <Input @on-change="handleClear"  @keyup.enter.native="handleSimpleSearch" clearable placeholder="输入关键字搜索" class="search-input" v-model="searchValue"/>
        <span @click="handleSimpleSearch" class="main-search-btn" type="primary"><Icon type="ios-search" /></span>
        <a href="javascript:void(0);" @click="togglePlusSearch" class="a-btn" type="primary"><Icon type="search"/>高级查询</a>
        <!-- 查询条件展示 -->
        <div class="simple-search-value-area">
          <Tag
          v-for='tag in simpleSearchTags'
          :key="tag.key"
          :name='tag.name'
          closable
          @on-close="handleTagClose">{{ tag.title }}:{{tag.value}}</Tag>
        </div>
        <!-- 高级查询 -->
        <div style="margin: 5px auto;padding:10px; border: 1px solid #eee; border-radis: 3px;" v-if="goPlusSearch">
          <Row style="padding: auto 5px;" v-for="item in plusSearchColumns"  :key="item.row">
              <Col span="8"
                style="padding: 10px 5px;"
                v-for="cell in item.list"
                :key="cell.key"
                >
                <Col span="4">
                  <div style="line-height:32px;height:32px;text-align: right; padding-right:10px;"> {{ cell.label }} :</div>
                </Col>
                <Col span="20">
                  <CommonFormCell
                  :cellProperty="cell"
                  @on-change="handlePlusSearchCellChange"
                  ></CommonFormCell>
                </Col>
              </Col>
          </Row>
          <Row>
            <Col span="4" offset="1">
              <Button @click="handleSearch" class="search-btn" type="primary"><Icon type="search"/>搜索</Button>
              <Button @click="handleSearch" class="search-btn" type="primary"><Icon type="search"/>重置</Button>
            </Col>
          </Row>
        </div>
      </div>
    </transition>
    <div class="handle-area">
      <div class="handle-area-left">
        <!-- <Button @click="handleCreate" class="search-btn handle-area-left-btn" type="primary"><Icon type="search"/>新增</Button>
        <Button @click="handleUpdate" class="search-btn handle-area-left-btn" type="warning"><Icon type="search"/>修改</Button>
        <Button @click="handleDelete" class="search-btn handle-area-left-btn" type="error"><Icon type="search"/>删除</Button> -->
      </div>
      <div class="handle-area-right">
        <span @click="toggleSearch" class="handle-area-right-btn"><Icon type="md-search" /></span>
        <span @click="refreshTable" class="handle-area-right-btn"><Icon type="md-refresh" /></span>
        <span @click="handleSearch" class="handle-area-right-btn"><Icon type="md-more" /></span>
      </div>
    </div>
    <Table
      ref="tablesMain"
      :data="insideTableData"
      :columns="insideColumns"
      :stripe="stripe"
      :border="border"
      :show-header="showHeader"
      :width="width"
      :height="height"
      :loading="loading"
      :disabled-hover="disabledHover"
      :highlight-row="highlightRow"
      :row-class-name="rowClassName"
      :size="size"
      :no-data-text="noDataText"
      :no-filtered-data-text="noFilteredDataText"
      @on-current-change="onCurrentChange"
      @on-select="onSelect"
      @on-select-cancel="onSelectCancel"
      @on-select-all="onSelectAll"
      @on-selection-change="onSelectionChange"
      @on-sort-change="onSortChange"
      @on-filter-change="onFilterChange"
      @on-row-click="onRowClick"
      @on-row-dblclick="onRowDblclick"
      @on-expand="onExpand"
    >
      <slot name="header" slot="header"></slot>
      <slot name="footer" slot="footer"></slot>
      <slot name="loading" slot="loading"></slot>
    </Table>
    <div v-if="searchable && searchPlace === 'bottom'" class="search-con search-con-top">
      <Select v-model="searchKey" class="search-col">
        <Option v-for="item in columns" v-if="item.key !== 'handle'" :value="item.key" :key="`search-col-${item.key}`">{{ item.title }}</Option>
      </Select>
      <Input placeholder="输入关键字搜索" class="search-input" v-model="searchValue"/>
      <Button class="search-btn" type="primary"><Icon type="search"/>&nbsp;&nbsp;搜索</Button>
    </div>
    <a id="hrefToExportTable" style="display: none;width: 0px;height: 0px;"></a>
  </div>
</template>

<script>
import TablesEdit from './edit.vue'
// import CommonFormCell from './common-form-cell.vue'
import UnionSearch from './unionSearch'
import handleBtns from './handle-btns'
import './index.less'
export default {
  name: 'Tables',
  components: {
    // 'CommonFormCell': CommonFormCell
    'UnionSearch': UnionSearch
  },
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    size: String,
    width: {
      type: [Number, String]
    },
    height: {
      type: [Number, String]
    },
    stripe: {
      type: Boolean,
      default: false
    },
    border: {
      type: Boolean,
      default: false
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    highlightRow: {
      type: Boolean,
      default: false
    },
    rowClassName: {
      type: Function,
      default () {
        return ''
      }
    },
    context: {
      type: Object
    },
    noDataText: {
      type: String
    },
    noFilteredDataText: {
      type: String
    },
    disabledHover: {
      type: Boolean
    },
    loading: {
      type: Boolean,
      default: false
    },
    /**
     * @description 全局设置是否可编辑
     */
    editable: {
      type: Boolean,
      default: false
    },
    /**
     * @description 是否可搜索
     */
    searchable: {
      type: Boolean,
      default: false
    },
    /**
     * @description 搜索控件所在位置，'top' / 'bottom'
     */
    searchPlace: {
      type: String,
      default: 'top'
    }
  },
  /**
   * Events
   * @on-start-edit 返回值 {Object} ：同iview中render函数中的params对象 { row, index, column }
   * @on-cancel-edit 返回值 {Object} 同上
   * @on-save-edit 返回值 {Object} ：除上面三个参数外，还有一个value: 修改后的数据
   */
  data () {
    return {
      insideColumns: [],
      insideTableData: [],
      edittingCellId: '',
      edittingText: '',
      searchValue: '',
      searchTitle: '',
      searchKey: '',
      goPlusSearch: false,
      // 简单查询对象tag数组
      simpleSearchTags: [],
      // 高级查询对象
      plusSearchObj: {
        name: '',
        date: '',
        sel: ''
      },
      // 高级查询默认语句测试
      plusSearchColumns: [
        {
          row: 1,
          list: [
            {
              type: 'input',
              name: 'Name',
              label: '姓名',
              placeholder: '填写名称',
              default: ''
            },
            {
              type: 'datetime', // 时间区间，使用两个默认值, 一个默认开始时间  一个结束时间
              name: 'Date',
              label: 'Date',
              placeholderStart: '填写Start',
              placeholderEnd: '填写End',
              defaultStart: '2018-11-11 00:00:00',
              defaultEnd: ''
            },
            {
              type: 'select', // 表单类型
              name: 'Sel', // 对应表单的字段名
              label: 'Sel', // 标签
              placeholder: '填写Sel', // 如名
              default: '1', // 默认值
              options: [
                {
                  key: 'one',
                  val: '1'
                },
                {
                  key: 'two',
                  val: '2'
                }
              ]
            }
          ]
        },
        {
          row: 2,
          list: [
            {
              type: 'radio', // 多选一
              name: 'Radi',
              label: 'Radio',
              placeholder: 'Radio',
              default: '1',
              options: [
                {
                  key: 'one',
                  val: '1'
                },
                {
                  key: 'two',
                  val: '2'
                }
              ]
            },
            {
              type: 'checkbox', // 多选一
              name: 'checkbox',
              label: 'checkbox',
              placeholder: 'checkbox',
              default: ['1'],
              options: [
                {
                  key: 'one',
                  val: '1'
                },
                {
                  key: 'two',
                  val: '2'
                }
              ]
            }
          ]
        }
      ]
    }
  },
  methods: {
    suportEdit (item, index) {
      item.render = (h, params) => {
        return h(TablesEdit, {
          props: {
            params: params,
            value: this.insideTableData[params.index][params.column.key],
            edittingCellId: this.edittingCellId,
            editable: this.editable
          },
          on: {
            'input': val => {
              this.edittingText = val
            },
            'on-start-edit': (params) => {
              this.edittingCellId = `editting-${params.index}-${params.column.key}`
              this.$emit('on-start-edit', params)
            },
            'on-cancel-edit': (params) => {
              this.edittingCellId = ''
              this.$emit('on-cancel-edit', params)
            },
            'on-save-edit': (params) => {
              this.value[params.row.initRowIndex][params.column.key] = this.edittingText
              this.$emit('input', this.value)
              this.$emit('on-save-edit', Object.assign(params, { value: this.edittingText }))
              this.edittingCellId = ''
            }
          }
        })
      }
      return item
    },
    surportHandle (item) {
      let options = item.options || []
      let insideBtns = []
      options.forEach(item => {
        if (handleBtns[item]) insideBtns.push(handleBtns[item])
      })
      let btns = item.button ? [].concat(insideBtns, item.button) : insideBtns
      item.render = (h, params) => {
        params.tableData = this.value
        return h('div', btns.map(item => item(h, params, this)))
      }
      return item
    },
    handleColumns (columns) {
      this.insideColumns = columns.map((item, index) => {
        let res = item
        if (res.editable) res = this.suportEdit(res, index)
        if (res.key === 'handle') res = this.surportHandle(res)
        return res
      })
    },
    setDefaultSearchKey () {
      this.searchKey = this.columns[0].key !== 'handle' ? this.columns[0].key : (this.columns.length > 1 ? this.columns[1].key : '')
      this.searchTitle = this.columns[0].key !== 'handle' ? this.columns[0].title : (this.columns.length > 1 ? this.columns[1].title : '')
    },
    handleClear (e) {
      if (e.target.value === '') this.insideTableData = this.value
    },
    handleSearch () {
      this.insideTableData = this.value.filter(item => item[this.searchKey].indexOf(this.searchValue) > -1)
    },
    handleTableData () {
      this.insideTableData = this.value.map((item, index) => {
        let res = item
        res.initRowIndex = index
        return res
      })
    },
    exportCsv (params) {
      this.$refs.tablesMain.exportCsv(params)
    },
    clearCurrentRow () {
      this.$refs.talbesMain.clearCurrentRow()
    },
    onCurrentChange (currentRow, oldCurrentRow) {
      this.$emit('on-current-change', currentRow, oldCurrentRow)
    },
    onSelect (selection, row) {
      this.$emit('on-select', selection, row)
    },
    onSelectCancel (selection, row) {
      this.$emit('on-select-cancel', selection, row)
    },
    onSelectAll (selection) {
      this.$emit('on-select-all', selection)
    },
    onSelectionChange (selection) {
      this.$emit('on-selection-change', selection)
    },
    onSortChange (column, key, order) {
      this.$emit('on-sort-change', column, key, order)
    },
    onFilterChange (row) {
      this.$emit('on-filter-change', row)
    },
    onRowClick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onRowDblclick (row, index) {
      this.$emit('on-row-dblclick', row, index)
    },
    onExpand (row, status) {
      this.$emit('on-expand', row, status)
    },
    // 在tables.vue上新增的功能
    toggleSearch () {
      this.searchable = !this.searchable
    },
    refreshTable (row, status) {
      this.$emit('on-refresh', row, status)
    },
    togglePlusSearch () {
      this.goPlusSearch = !this.goPlusSearch
    },
    setSearchTitle (title) {
      this.searchTitle = title
    },
    handlePlusSearchCellChange (key, value) {
      this.plusSearchObj[key] = value
    },
    handleTagClose (e, name) {
      // 删除该下表的tag
      for (let i = 0; i < this.simpleSearchTags.length; i++) {
        if (this.simpleSearchTags[i].name === name) {
          this.simpleSearchTags.splice(i, 1)
        }
      }
    },
    handleSimpleSearch () {
      // 检查是否含有该元素 , 有则直接修改
      let hasSearchKeyInSimpleSearchTags = false
      for (let i = 0; i < this.simpleSearchTags.length; i++) {
        if (this.simpleSearchTags[i].key === this.searchKey) {
          hasSearchKeyInSimpleSearchTags = true
          this.simpleSearchTags[i].value = this.searchValue
        }
      }
      if (!hasSearchKeyInSimpleSearchTags) {
        this.simpleSearchTags.push({
          name: this.searchKey,
          key: this.searchKey,
          title: this.searchTitle,
          value: this.searchValue
        })
      }
      this.handleSearch()
    }
  },
  watch: {
    columns (columns) {
      this.handleColumns(columns)
      this.setDefaultSearchKey()
    },
    value (val) {
      this.handleTableData()
      if (this.searchable) this.handleSearch()
    }
  },
  mounted () {
    this.handleColumns(this.columns)
    this.setDefaultSearchKey()
    this.handleTableData()
  }
}
</script>
